{
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4-final"
  },
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2,
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# sklearn中的回归问题"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn import datasets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "boston = datasets.load_boston()\n",
    "X = boston.data\n",
    "y = boston.target\n",
    "\n",
    "X = X[y < 50.0]\n",
    "y = y[y < 50.0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "(490, 13)"
     },
     "metadata": {},
     "execution_count": 3
    }
   ],
   "source": [
    "X.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=666)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "## sklearn 中 的线性回归"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "lin_reg = LinearRegression()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)"
     },
     "metadata": {},
     "execution_count": 9
    }
   ],
   "source": [
    "lin_reg.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "array([-1.15625837e-01,  3.13179564e-02, -4.35662825e-02, -9.73281610e-02,\n       -1.09500653e+01,  3.49898935e+00, -1.41780625e-02, -1.06249020e+00,\n        2.46031503e-01, -1.23291876e-02, -8.79440522e-01,  8.31653623e-03,\n       -3.98593455e-01])"
     },
     "metadata": {},
     "execution_count": 10
    }
   ],
   "source": [
    "lin_reg.coef_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "32.59756158869974"
     },
     "metadata": {},
     "execution_count": 11
    }
   ],
   "source": [
    "lin_reg.intercept_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "0.8009390227581031"
     },
     "metadata": {},
     "execution_count": 12
    }
   ],
   "source": [
    "lin_reg.score(X_test, y_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "## knn Regresser"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "0.602674505080953"
     },
     "metadata": {},
     "execution_count": 14
    }
   ],
   "source": [
    "from sklearn.neighbors import KNeighborsRegressor\n",
    "knn_reg = KNeighborsRegressor()\n",
    "knn_reg.fit(X_train, y_train)\n",
    "knn_reg.score(X_test, y_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "Fitting 3 folds for each of 60 candidates, totalling 180 fits\n[Parallel(n_jobs=-1)]: Using backend LokyBackend with 4 concurrent workers.\n[Parallel(n_jobs=-1)]: Done 180 out of 180 | elapsed:    1.7s finished\n"
    },
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "GridSearchCV(cv='warn', error_score='raise-deprecating',\n             estimator=KNeighborsRegressor(algorithm='auto', leaf_size=30,\n                                           metric='minkowski',\n                                           metric_params=None, n_jobs=None,\n                                           n_neighbors=5, p=2,\n                                           weights='uniform'),\n             iid='warn', n_jobs=-1,\n             param_grid=[{'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n                          'weights': ['uniform']},\n                         {'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n                          'p': [1, 2, 3, 4, 5], 'weights': ['uniform']}],\n             pre_dispatch='2*n_jobs', refit=True, return_train_score=False,\n             scoring=None, verbose=1)"
     },
     "metadata": {},
     "execution_count": 15
    }
   ],
   "source": [
    "from sklearn.model_selection import GridSearchCV\n",
    "\n",
    "param_grid =[{\"weights\":[\"uniform\"],\"n_neighbors\":[i for i in range(1,11)]},{\"weights\":[\"uniform\"],\"n_neighbors\":[i for i in range(1,11)],\"p\":[i for i in range(1,6)]}]\n",
    "\n",
    "knn_reg = KNeighborsRegressor()\n",
    "grid_search = GridSearchCV(knn_reg, param_grid, n_jobs=-1, verbose=1)\n",
    "grid_search.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "{'n_neighbors': 3, 'p': 1, 'weights': 'uniform'}"
     },
     "metadata": {},
     "execution_count": 18
    }
   ],
   "source": [
    "grid_search.best_params_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "0.5736410172685177"
     },
     "metadata": {},
     "execution_count": 19
    }
   ],
   "source": [
    "grid_search.best_score_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "KNeighborsRegressor(algorithm='auto', leaf_size=30, metric='minkowski',\n                    metric_params=None, n_jobs=None, n_neighbors=3, p=1,\n                    weights='uniform')"
     },
     "metadata": {},
     "execution_count": 20
    }
   ],
   "source": [
    "grid_search.best_estimator_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "0.733942168303894"
     },
     "metadata": {},
     "execution_count": 21
    }
   ],
   "source": [
    "grid_search.best_estimator_.score(X_test, y_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ]
}